package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.SHOP_GEO_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;

    //定义一个线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 根据id查询商铺
     * @param id
     * @return
     */
    @Override
    public Result queryShopById(Long id) {
//        return cachePenetration(id);
        return cacheBreakdown1(id);
//        return cacheBreakdown2(id);

    }

    /**
     * 根据商铺类型分页查询规定距离内商铺信息
     * @param typeId
     * @param current
     * @param x
     * @param y
     * @return
     */
    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 1.判断是否需要根据坐标查询
        if (x == null || y == null) {
            // 不需要坐标查询，按数据库查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }

        // 2.计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        // 3.查询redis、按照距离排序、分页。结果：shopId、distance
        String key = SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo() // GEOSEARCH key BYLONLAT x y BYRADIUS 10 WITHDISTANCE
                .search(
                        key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
                );
        // 4.解析出id
        if (results == null) {
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from) {
            // 没有下一页了，结束
            return Result.ok(Collections.emptyList());
        }
        // 4.1.截取 from ~ end的部分
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(result -> {
            // 4.2.获取店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            // 4.3.获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });
        // 5.根据id查询Shop
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        // 6.返回
        return Result.ok(shops);
    }

    //解决缓存击穿(逻辑过期)
    private Result cacheBreakdown2(Long id){
        HashOperations<String, Object, Object> opsForHash = stringRedisTemplate.opsForHash();

        Map<Object, Object> entries = opsForHash.entries(RedisConstants.CACHE_SHOP_KEY+id);

        //默认热点数据都已提前存入缓存，如果未命中直接判定为不存在该数据
        if(entries.size() == 0){
            return Result.fail("不存在该店铺");
        }

        RedisData cacheShopData = BeanUtil.fillBeanWithMap(entries, new RedisData(), false);
        Shop shop = JSONUtil.toBean((String) cacheShopData.getData(), Shop.class);

        //缓存还未逻辑过期，返回商铺信息
        if(cacheShopData.getExpireTime().isAfter(LocalDateTime.now())){
            return Result.ok(shop);
        }
        //缓存已经逻辑过期
        //1.尝试获取互斥锁
        try {
        boolean b = setLock(id);
        if(!b){
                //获取锁失败,直接返回商铺信息
                return Result.ok(shop);
            }
            //获取锁成功
            //2.开启独立线程，查询数据库，更新数据写入缓存
            CACHE_REBUILD_EXECUTOR.submit(() ->{
                Shop shopById = this.getById(id);
                Map<String, Object> shopMap = BeanUtil.beanToMap(new RedisData(LocalDateTime.now().plusSeconds(20L), JSONUtil.toJsonStr(shopById)),
                        new HashMap<>(),
                        CopyOptions.create()
                                .setIgnoreNullValue(true)
                                .setFieldValueEditor((fieldName,fieldValue)-> fieldValue.toString()));
                opsForHash.putAll(RedisConstants.CACHE_SHOP_KEY+id,shopMap);
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            releaseLock(id);
        }

        return Result.ok(shop);
    }

    //同时解决缓存击穿(互斥锁)和缓存穿透的问题
    private Result cacheBreakdown1(Long id){
        HashOperations<String, Object, Object> opsForHash = stringRedisTemplate.opsForHash();

        Map<Object, Object> entries = opsForHash.entries(RedisConstants.CACHE_SHOP_KEY + id);
        Shop cacheShop = BeanUtil.fillBeanWithMap(entries, new Shop(), false);

        //redis中没有数据，则去数据库中查询并写入redis
        if(entries.size() == 0){
            try {
                //为防止缓存击穿
                //去数据库查询数据写入缓存前先获取互斥锁
                if(!setLock(id)){
                    //获取锁失败，线程休眠一段时间，再尝试访问redis中的数据
                    Thread.sleep(30);
                    return cacheBreakdown1(id);
                }
                //获取互斥锁成功，查询数据
                cacheShop = this.getById(id);
                //模拟查询写入缓慢的情况
//                Thread.sleep(60);

                //数据库也不存在该数据，缓存空数据到redis，防止缓存穿透
                if(cacheShop == null){
                    opsForHash.put(RedisConstants.CACHE_SHOP_KEY+id,"empty","");
                    stringRedisTemplate.expire(RedisConstants.CACHE_SHOP_KEY+id,120L, TimeUnit.SECONDS);
                    return Result.fail("商铺不存在");
                }

                //数据库中数据存在，将数据库中数据存入redis
                cacheShop.setDistance(1.0);
                //将对象转换为hashmap,并将字段值都转换为string类型
                Map<String, Object> shopMap = BeanUtil.beanToMap(cacheShop,new HashMap<>(),
                        CopyOptions.create()
                                .setIgnoreNullValue(true)
                                .setFieldValueEditor((fieldName,fieldValue)-> fieldValue.toString()));
                opsForHash.putAll(RedisConstants.CACHE_SHOP_KEY+id,shopMap);
                stringRedisTemplate.expire(RedisConstants.CACHE_SHOP_KEY+id,3600, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                //释放互斥锁
                releaseLock(id);
            }
        }
        else if(entries.containsKey("empty")){
            //如果此处获取到的数据为之前在redis中预设好的“空数据”，代表数据库中没有该数据，直接返回失败信息
            return Result.fail("不存在该商铺");
        }


        return Result.ok(cacheShop);
    }

    //解决缓存穿透的方案
    private Result cachePenetration(Long id){
        HashOperations<String, Object, Object> opsForHash = stringRedisTemplate.opsForHash();

        Map<Object, Object> entries = opsForHash.entries(RedisConstants.CACHE_SHOP_KEY + id);
        Shop cacheShop = BeanUtil.fillBeanWithMap(entries, new Shop(), false);

        if(entries.size() == 0){
            cacheShop = this.getById(id);
            //数据库也不存在该数据，缓存空数据到redis，防止缓存穿透
            if(cacheShop == null){
                opsForHash.put(RedisConstants.CACHE_SHOP_KEY+id,"empty","");
                stringRedisTemplate.expire(RedisConstants.CACHE_SHOP_KEY+id,120L, TimeUnit.SECONDS);
                return Result.fail("商铺不存在");
            }

            cacheShop.setDistance(1.0);
            log.info("cache shop : {}", cacheShop);
            //将对象转换为hashmap,并将字段值都转换为string类型
            Map<String, Object> shopMap = BeanUtil.beanToMap(cacheShop,new HashMap<>(),
                    CopyOptions.create()
                            .setIgnoreNullValue(true)
                            .setFieldValueEditor((fieldName,fieldValue)-> fieldValue.toString()));
            //将商户信息存入Redis
            opsForHash.putAll(RedisConstants.CACHE_SHOP_KEY+id,shopMap);
            stringRedisTemplate.expire(RedisConstants.CACHE_SHOP_KEY+id,3600, TimeUnit.SECONDS);
        }else if(entries.get("empty").equals("")){
            return Result.fail("不存在该商铺");
        }


        return Result.ok(cacheShop);
    }

    //设置互斥锁
    private boolean setLock(Long id){
        Boolean b = stringRedisTemplate.opsForValue().setIfAbsent("mutex:" + id, "lock", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(b);
    }

    //释放互斥锁
    private void releaseLock(Long id){
        stringRedisTemplate.delete("mutex:" + id);
    }
}
